package cn.wolfcode.shop.cloud.resolver;

import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.service.RedisService;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import cn.wolfcode.shop.cloud.util.MemberKeyPrefix;
import cn.wolfcode.shop.cloud.util.UserValidAnno;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private RedisService redisService;

    @Override
    //判断你的参数类型是否符合条件
    public boolean supportsParameter(MethodParameter methodParameter) {
        //判断参数类型是否符合==User类型,并且贴有@UserValidAnno的注解
        return methodParameter.getParameterType() == User.class && methodParameter.getParameterAnnotation(UserValidAnno.class)!=null;
    }

    @Override
    //向redis中去取值,判断User类型
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //先获取一个请求对象
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        //可以获得token的值
        String token = CookieUtil.getCookieValue(request, "userToken");
        //上redis中去取值
        User user = redisService.get(MemberKeyPrefix.USER_TOKEN, token, User.class);
        return user;
    }
}
